/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.edmo.fastener.business;

import com.edmo.fastener.jms.OrderService;
import com.edmo.fastener.slave.IocBean;
import java.io.File;
import java.util.logging.Level;
import javax.crypto.Cipher;
import javax.crypto.SealedObject;
import javax.crypto.SecretKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 *
 * @author Alexx
 */
public class CheckFiles implements Runnable {
    private ApplicationContext context = new ClassPathXmlApplicationContext("Spring-Module.xml");
    private IocBean dir = (IocBean) context.getBean("folder");
    private ApplicationContext ctx = new ClassPathXmlApplicationContext("sender.xml");
    private OrderService orderService = (OrderService) ctx.getBean("orderService");
    private static Logger log = LoggerFactory.getLogger(CheckFiles.class);
    private static WorkQueue wq = new WorkQueue(10);

    private void findFile(String dir) {
        String files;
        File folder = new File(dir);
        File[] listOfFiles = folder.listFiles();

        for (int i = 0; i < listOfFiles.length; i++) {

            if (listOfFiles[i].isFile()) {
                files = listOfFiles[i].getName();
                if (files.endsWith(".txt") || files.endsWith(".TXT")) {
                    log.info(dir + "\\" + files.toString());
                    File oldfile =new File(dir + "\\" +files.toString());
                    File newfile =new File(dir + "\\" +files.toString() + ".tmp");
                    oldfile.renameTo(newfile);
                    //wq.execute(new OrderProcessing(dir + "\\" +files.toString() + ".tmp", files.toString()));
                    orderService.sendOrder(dir + "\\" +files.toString() + ".tmp", files.toString(), ListofCustomersnSuppliers.getOrderId().toString());
                }
            }
        }
    }
    
    public void check(){
        String rootFolder = dir.getName();
        for (int i = 1; i < 501; i++){
            findFile(rootFolder + "\\CUSTOMERS\\" + "C" + i);
        }
    }

    public void run() {
        System.out.println("---Server started--- " + System.currentTimeMillis());
        while(true){
           check();
            try {
                Thread.sleep(500);
            } catch (InterruptedException ex) {
                log.error(ex.toString());
            }
        }
    }
}
